﻿// ==================================================================================
// = Bot Initialization																=
// ==================================================================================
var MakeBot		= require('../index');
var fs			= require('fs');
var AUTH		= 'AUTH';
var USERID		= 'USERID';
var ROOMID		= 'ROOMID';
var bot			= new MakeBot(AUTH,USERID,ROOMID);

var upVotes = 0, downVotes = 0, songSnags = 0;
var songName = '', lastScore = '';

var roomUsers	= [];
var roomDJs		= [];
var lastActive	= [];
var warnedDJs	= [];

var modList		= [];
var blackList	= [];

// ==================================================================================
// = Custom Functions																=
// ==================================================================================

isMod	= function(ID) { for (var i=0; i < modList.length; i++) { var mod = false; if (ID == modList[i]) { mod = true; break; } } return mod; };

getName = function(ID) {
	var userName = '';
	for (var i=0; i < roomUsers.length; i++) { if (ID == roomUsers[i].userid) { userName = roomUsers[i].name; break; } }
	return userName;
}

resetIdle	= function(ID) { lastActive[ID] = new Date(); if (ID in warnedDJs) { delete warnedDJs[ID];} };
getIdle		= function(ID) { var idleTime = new Date().getTime() - lastActive[ID].getTime(); return idleTime; }

// ==================================================================================
// = Timed Events / Reminders														=
// ==================================================================================

// AFK-Detection, Warn, & Kick
heartbeat = function() {
	for (var i=0; i < roomDJs.length; i++) {
		if (isMod(roomDJs[i]) == false) {
			if (getIdle(roomDJs[i]) > 10*60*1000 && !(warnedDJs[roomDJs[i]] == true)) {
				warnedDJs[roomDJs[i]] = true;
				bot.speak( '' + getName[roomDJs[i]] + ' please remember it\'s okay to idle while you Minecraft, but stay active if you\'re DJing!' );
			}
			if (getIdle(roomDJs[i]) > 15*60*1000) {
				bot.speak( '' + getName[roomDJs[i]] + ', try and make sure to stay active!' );
				bot.remDj(roomDJs[i]);
			}
		} else {
			lastActive[roomDJs[i]] = new Date();
		}
	}
}; setInterval(heartbeat, 5000);

// Server Reminder Message!
setInterval(function() { bot.speak('Did you know that we have our own Minecraft server? Grab the IP in the room info & check it out!'); }, 20*60*1000);

// ==================================================================================
// = Track Votes & Snags															=
// ==================================================================================
bot.on("update_votes", function(data) {

	// Reset Idle Counter For Users Who Voted
    var voteLog = data.room.metadata.votelog;
	for (var i=0; i < voteLog.length; i++) {
		var user = voteLog[i];
		var id = user[0];
		resetIdle(id);
	}

	// Update Vote Counts
	upVotes = data.room.metadata.upvotes;
	downVotes = data.room.metadata.downvotes;

});

// Update Snagged Count
bot.on("snagged", function(data) { songSnags = songSnags + 1; });

// ==================================================================================
// = Song Change / Auto-Bop															=
// ==================================================================================
bot.on('newsong', function(data) {

	// Save Previous Song Stats For "/lastsong"
	if (songName !== '') { lastScore = '♫ ' + songName + ' earned: ▲' + upVotes + ' ▼' + downVotes + ' ♥' + songSnags + ''; }

	// Reset Song Stats
	songName = '"' + data.room.metadata.current_song.metadata.song + '" by ' + data.room.metadata.current_song.metadata.artist;
	upVotes = data.room.metadata.upvotes;
	downVotes = data.room.metadata.downvotes;
	songSnags = 0;

	// Start Auto-Bob
	bot.vote('up');

});

// ==================================================================================
// = Bot Initialization / Custom Intros / User Logging								=
// ==================================================================================
bot.on('registered', function(data) {

	// Store Username & ID
	var name	= data.user[0].name;
	var id		= data.user[0].userid;

	// If Bot, We Need To Initialize Some Things
	if (id == USERID) {

		// Create Moderator & DJ Lists
		bot.roomInfo(function(data) { modList = data.room.metadata.moderator_id; });
		bot.roomInfo(function(data) { roomDJs = data.room.metadata.djs; });

		// Create User List & Initialize Idle Counters
		bot.roomInfo(function(data) { roomUsers = data.users; });
		for (var i=0; i < roomUsers.length; i++) { resetIdle(roomUsers[i].userid); }

		// Load Blacklist File
		blackList = fs.readFileSync('./banned.txt', 'utf8').split(',');

		// Save Current Song Stats For "/lastsong"
		bot.roomInfo(function(data) {
			if (data.room.metadata.current_song) {
				songName = data.room.metadata.current_song.metadata.song;
				upVotes = data.room.metadata.upvotes;
				downVotes = data.room.metadata.downvotes;
			}
		});
	}

	// If The New User Is Blacklisted, Kick Them Out!
	for (var i=0; i < blackList.length; i++) {
		if (id == blackList[i]) {
			bot.bootUser(id, 'You are on the blacklist.');
			break;
		}
	}

	// Rebuild User List With New User & Initialize Their Idle Counter
	bot.roomInfo(function(data) { roomUsers = data.users; });
	resetIdle(id);

	// Skip The Bot From Logging & Intros
	if (id == USERID) { }

	// Custom Intros
	else if (id == 'MYID') { bot.speak( 'Bow down! The great ' + name + ' is in the house!' ); }
	else if (id == 'ZEROID') { bot.speak( '' + name + ' is immortal... That explains everything!' ); }
	else if (id == 'DIONID') { bot.speak( '' + name + ' is here. Welcome the god of wine and ecstasy!' ); }
	else if (id == 'SHEWSID') { bot.speak( 'Oh great... ' + name + '. The little bitch of bitch kingdom!' ); }

	// Log All Other Users
	else { console.log( '' + name + ' joined the room. (id: ' + id + ')' ); }

});

// ==================================================================================
// = User Deregisters From Room														=
// ==================================================================================
bot.on("deregistered", function(data) {

	// Rebuild DJ List Incase User Was A DJ
	bot.roomInfo(function(data) { roomDJs = data.room.metadata.djs; });

	// Rebuild User List Without Leaving User
	bot.roomInfo(function(data) { roomUsers = data.users; });

});

// ==================================================================================
// = Chat Commands / Chat Logging													=
// ==================================================================================
bot.on('speak', function(data){

	// Store Username, ID, & What Was Said
	var name	= data.name;
	var id		= data.userid;
	var text	= data.text;

	// When Someone Speaks, Reset Their Idle Counter
	resetIdle(id);

	// Skip The Bot From Logging & Commands
	if (id == USERID) { }

	// Room Information - "/info"
	else if (text == '/info') {
		bot.speak( 'Dubstep Minecrafters Unite! Please read the room description for the Server IP and genre list.' );
	}

	// Help (Command List) - "/help"
	else if (text == '/help') {
		bot.speak( 'Commands: /help, /info, /lastsong, /dance, /chilltime, /hypetime, /grimetime, /drinksonme, /smokesesh' );
	}

	// Manual Bot Dance - "/dance"
	else if (text == '/dance') { bot.vote('up'); }

	// Lame Song (Skip If Bot Is DJ) - "/lame"
	else if (text == '/lame') {	
		if (isMod(id) == true) {
			bot.vote('down');
			bot.stopSong();
		}
	}

	// Last Song's Stats - "/lastsong"
	else if (text == '/lastsong') {
		if (lastScore !== '') {
			bot.speak(lastScore);
		} else {
			bot.speak('I\'m sorry, I wasn\'t paying attention...');
		}
	}

	// Vote For Slower Music - "/chilltime"
	else if (text == '/chilltime') {
		bot.speak( '' + name + ' thinks it\'s time to slow those beats down.' );
	}

	// Vote For Faster Music - "/hypetime"
	else if (text == '/hypetime') {
		bot.speak( '' + name + ' is in the mood for some faster tracks.' );
	}

	// Vote For Dirtier Music - "/grimetime"
	else if (text == '/grimetime') {
		bot.speak( '' + name + ' doesn\'t think the music is dirty enough.' );
	}

	// TT's Trademark Smokesesh - "/smokesesh"
	else if (text == '/smokesesh') {
		bot.speak( '' + name + ' has declared a smoke sesh, whip out the bongs!' );
	}

	// Buy A Round Of Drinks - "/drinksonme"
	else if (text == '/drinksonme') {
		bot.speak( 'Everyone drink up! Drinks are on ' + name + '!' );
	}

	// Midori's Signature "SHOTS!" Drinking Game
	else if (text.match(/shot/i)) {
		bot.speak( 'SHOTS! ' + name + ' said "shot"! Time for a shot!' );
	}

	// Logs All Non-Command Chat
	else { console.log( '' + name + ': ' + text + '' ); }

});

// ==================================================================================
// = New DJ / DJ Logging															=
// ==================================================================================
bot.on('add_dj', function(data) {

	// Store Username & ID
	var name	= data.user[0].name;
	var id		= data.user[0].userid;

	// Rebuild DJ List With New DJ
	bot.roomInfo(function(data) { roomDJs = data.room.metadata.djs; });

	// Reset New DJ's Idle Counter
	resetIdle(id);

	// Announce The New DJ & Log Them
	bot.speak( '' + name + ' is now up on the decks!' );
	console.log( '' + name + ' started DJing. (id: ' + id + ')' );

});

// ==================================================================================
// = Remove DJ / DJ Leaves															=
// ==================================================================================
bot.on('rem_dj', function(data) {

	// Store User ID
	var id = data.user[0].userid;

	// Rebuild DJ List Without Old DJ
	bot.roomInfo(function(data) { roomDJs = data.room.metadata.djs; });

	// Reset Old DJ's Idle Counter (Not Needed, But Here Incase DJ Steps Down)
	resetIdle(id);

});

// ==================================================================================
// = New / Remove Moderator (Update modList)										=
// ==================================================================================
bot.on('new_moderator', function(data) { bot.roomInfo(function(data) { modList = data.room.metadata.moderator_id; }); });
bot.on('rem_moderator', function(data) { bot.roomInfo(function(data) { modList = data.room.metadata.moderator_id; }); });
